package test.client.thread.message;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.packet.Message;

import test.client.thread.ClientThread;

public class ClientReceiverThread extends ClientThread {
	private boolean isChatDone = false;
	
	@Override
	public void run() {
		this.notifyStarted();
		
		try {
			this.login();
			
			Roster roster = this.connection.getRoster();
			for (RosterEntry entry : roster.getEntries()) {
				log.debug(entry.getUser());
			}
			
			while (this.getStatus() == Status.RUNNING && !this.isChatDone) {
				Thread.sleep(3000);	
			}
			
			this.setResult(Result.SUCCESS);
		}
		catch (Exception e) {
			e.printStackTrace();
			this.setResult(Result.FAILURE);
		}
		finally {
			this.setStatus(Status.COMPLETED);
		}
		
		this.notifyStopped();
	}
	
	@Override
	public void processMessage(Message message) {
		if (message.getType() != Message.Type.chat) return;
		
		try {
			// If "bye" message is received, go to offline
			if ("bye".equals(message.getBody())) {
				this.isChatDone = true;
				return;
			}
			
			this.sendMessage(message.getBody() + " echo", message.getFrom());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void processMessage(Chat chat, Message message) {
		super.processMessage(chat, message);
		this.processMessage(message);
	}

	public static void main(String[] args) {
		ClientReceiverThread thread = new ClientReceiverThread();
		thread.setUsername("user000000");
		thread.setPassword("welcome1");
		thread.setId(0);
				
		thread.setStatus(Status.RUNNING);
		thread.run();
	}
}
